<template>
    <div class="account_container">
        <!-- 我的账户 -->
        <div class="account">
            <div class="amount_card">
                <div class="amount_card_info">
                    <div>可用余额：</div>
                    <div class="price">{{ state.balance || '-' }}</div>
                </div>
                <div class="amount_card_btn">
                    <el-button type="primary" @click="onWithdrawals" v-auth="'pay_account:Withdrawal'">提现</el-button>
                    <el-button @click="onRechargeDia" v-auth="'pay_account:recharge'">充值</el-button>
                </div>
            </div>

            <div class="income_part">
                <div class="income_order">
                    <div>待结算的订单收入：</div>
                    <div
                        v-if="state.waitOrderIncome"
                        :class="[hasOrderIncomeAuth && state.waitOrderIncome > 0 ? 'num pointer' : 'num']"
                        @click="viewSettleOrder()">
                        {{ `￥${state.waitOrderIncome}` }}
                    </div>
                    <div v-else>-</div>
                </div>
                <el-divider class="divider" direction="vertical" />
                <div class="income_bill">
                    <div>待结算的分账收入：</div>
                    <div class="num">{{ state.waitSubAccountIncome || '-' }}</div>
                </div>
            </div>

            <div class="title">
                账户收支明细
                <span>资金流水明细是账户流水明细，未结算订单不会产生资金出入账。</span>
            </div>

            <!-- 查询 -->
            <div class="search">
                <el-form ref="paramsRef" :model="params" label-width="80">
                    <el-row :gutter="24">
                        <el-col :span="6">
                            <el-form-item label="动向" prop="flowDirection">
                                <el-select v-model="params.flowDirection" placeholder="全部">
                                    <el-option
                                        v-for="item in options"
                                        :label="item.label"
                                        :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="变动类型" prop="changeType">
                                <el-select v-model="params.changeType" placeholder="全部">
                                    <el-option
                                        v-for="item in typeOptions"
                                        :label="item.label"
                                        :value="item.value"
                                        :key="item.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="订单编号" prop="objectSn">
                                <el-input v-model="params.objectSn" placeholder="输入订单编号"> </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="来源" label-width="50" prop="source">
                                <el-input v-model="params.source" placeholder="输入企业名称、用户姓名、登录号">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="来源门店" prop="shopId">
                                <el-select v-model="params.shopId" placeholder="全部">
                                    <el-option label="全部" :value="0" />
                                    <el-option
                                        v-for="item in shopList"
                                        :key="item.shopId"
                                        :label="item.shopName"
                                        :value="item.shopId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="变动时间" prop="createdAt">
                                <el-date-picker
                                    v-model="params.createdAt"
                                    type="daterange"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :default-time="defaultDateRange"
                                    range-separator="-"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label-width="0">
                                <el-button type="primary" @click="onSearch">查询</el-button>
                                <el-button plain @click="onReset">清空</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" class="zw-form-btns">
                            <el-button plain v-auth="'pay_account:export'" @click="onExport">导出</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 列表 -->
            <div class="table_card">
                <el-table :data="state.list" stripe>
                    <el-table-column prop="flowDirectionName" width="60" label="动向"></el-table-column>
                    <el-table-column prop="changeTypeName" width="110" label="变动类型"></el-table-column>
                    <el-table-column prop="" min-width="110" label="订单编号">
                        <template v-slot="{ row }">
                            <span v-if="row.changeType == 1" class="link" @click="viewOrderDetail(row)">{{
                                row.objectSn || '-'
                            }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="shopName" label="来源门店">
                        <template v-slot="{ row }">
                            <span v-if="row.changeType == 1">{{ row.shopName || '-' }}</span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="changeAmount" min-width="80" label="金额">
                        <template v-slot="{ row }">
                            <!-- 按入账和出账区分 -->
                            <span v-if="row.flowDirection === 'income'">+</span
                            ><span v-if="row.flowDirection === 'expenditure'">-</span>
                            <span>￥{{ priceFilter(floatDivide(Math.abs(row.changeAmount), 100) || 0) }}</span>
                            <el-tooltip placement="top" v-if="row.changeType == 1">
                                <template #content>
                                    分成：￥{{ priceFilter(floatDivide(row.splitPortion, 100)) }}
                                </template>
                                <img class="icon_img" src="@/assets/imgs/sys/question-circle.png" />
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" width="180" label="变动时间"></el-table-column>
                    <el-table-column prop="remark" min-width="110" label="备注">
                        <template v-slot="{ row }">
                            <div v-if="row.changeType == 1 || row.changeType == 5">-</div>
                            <div v-else>
                                <!--区分 \r 换行 -->
                                <div v-for="(item, index) in (row.remark || '-').split('\\r')" :key="index">
                                    {{ item }}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="source" min-width="110" label="来源信息">
                        <template v-slot="{ row }">
                            <template v-if="row.changeType == 2 || row.changeType == 3">-</template>
                            <template v-else>
                                <!--区分 \r 换行 -->
                                <!-- <div v-for="(item, index) in (row.source || '-').split('\r')" :key="index">
                                    {{ item }}
                                </div> -->
                                <div>{{ row.changeType == 1 ? '企业名称' : '姓名' }}：{{ row.sourceName }}</div>
                                <div>登录号：{{ row.sourceLoginNo }}</div>
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination_card">
                <Pagination
                    :pageSize="params.perPage"
                    :currentPage="params.page"
                    :total="state.total"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>

        <!-- 提现弹框 -->
        <div class="withdrawals_dialog">
            <el-dialog v-model="state.show" title="申请提现" width="400px" @closed="onClosed">
                <div class="content">
                    <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                        <el-form-item label="可用余额">{{ state.balance }}</el-form-item>
                        <el-form-item label="提现至">{{ state.bankCardNumber }}</el-form-item>
                        <el-form-item label="提现金额" prop="amount" :rules="rules.amount">
                            <el-input-number
                                class="input_width_200"
                                v-model="form.amount"
                                :min="0.01"
                                :max="+state.money"
                                :precision="2"
                                :controls="false"
                                placeholder="请输入大于0的数字" />
                            <span class="margin_left_2px"> 元</span>
                        </el-form-item>
                        <el-form-item label="  ">
                            <div class="desc">预计1个工作日到账</div>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="onCofirm(formRef)">立即提现</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>

        <!-- 充值弹窗 -->
        <RechargeDia v-model="state.rechargeShow" @closed="getData" />
    </div>
</template>

<script setup>
import RechargeDia from './rechargeDia.vue';
import Pagination from '@/components/Pagination.vue';
import Unsettled from './unsettled.vue';
import request from '@/request';
import { floatMultiply, floatDivide, exportExc, dealObjectEmptyValue } from '@/commons/utils';
import store from '@/store';
import storage from '@/commons/storage';
import { ElMessage } from 'element-plus';
import { reactive, ref, computed, onMounted } from 'vue';
const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;

const emit = defineEmits(['changeTab']);

const props = defineProps({
    shopList: { type: Array, default: () => [] }
});
const Address = '?Address=' + location.origin + location.pathname;
const options = [
    { label: '全部', value: '' },
    { label: '入账', value: 'income' },
    { label: '出账', value: 'expenditure' }
];
const typeOptions = [
    { label: '全部', value: 0 },
    { label: '分账收入', value: 5 },
    { label: '订单收入', value: 1 },
    { label: '充值', value: 2 },
    { label: '提现', value: 3 },
    { label: '企业打款（C端提现）', value: 4 }
];

const defaultDateRange = [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)];
const entObj = storage.get('ZW-TENANT-LOGINNO');

const params = reactive({
    // accountId: storage.get('ZW-TENANT-ID'),
    perPage: 10,
    page: 1,
    flowDirection: '',
    changeType: 0,
    objectSn: '',
    source: '',
    shopId: 0,
    createdAt: []
});
const state = reactive({
    show: false,
    payShow: false,
    // 待结算的订单收入（Number）
    waitOrderIncome: '',
    // 待结算的分账收入（string）
    waitSubAccountIncome: '',
    list: [],
    total: 0,
    money: 0, // 可用余额
    balance: '', // 可用余额
    bankCardNumber: '', // 银行卡号，

    /* 充值弹窗 */
    rechargeShow: false
});

// 是否有待结算订单权限
const hasOrderIncomeAuth = computed(() => {
    return permissions.has('pay_for_order');
});

// 提现弹窗
const formRef = ref(null);
const amountValidator = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入提现金额'));
    } else if (value < 0.01) {
        callback(new Error('提现金额不能小于0.01元'));
    } else if (value > state.money) {
        callback(new Error('提现金额不能大于可用余额'));
    } else {
        callback();
    }
};
const rules = {
    amount: [
        { required: true, message: '请输入提现金额', trigger: 'blur' },
        { validator: amountValidator, trigger: 'blur' }
    ]
};
const form = reactive({
    amount: null,
    agreementNo: '',
    loginNo: entObj.loginNo
});
// 打开提现弹框
const onWithdrawals = () => {
    if (+state.money === 0) {
        ElMessage.error('可用余额为0，不可申请提现');
        return;
    }
    state.show = true;
};
// 关闭提现弹框
const onClosed = () => {
    formRef.value.resetFields();
    form.amount = null;
};

// 提现确认
const onCofirm = async formEl => {
    if (!formEl) return;
    await formEl.validate(async valid => {
        if (valid) {
            let result = {};
            Object.assign(result, form);
            result.amount = floatMultiply(result.amount, 100).toString();
            const { data } = await request('baofuWithdraw', result);
            if (data.url) {
                const url = data.url + Address;
                storage.set('ZW-LOGIN_NO', props.loginNo);
                window.open(url, '_self');
            }
        }
    });
};

// 充值
const onRechargeDia = () => {
    state.rechargeShow = true;
};

// 启动的对公卡列表
const getCardList = () => request('baofuFindBindBankCards', { loginNo: entObj.loginNo });
// 账户余额查询
const getBalance = () => request('baofuBalance', { loginNo: entObj.loginNo });
const getData = async () => {
    getList();
    const [res1, res2] = await Promise.all([getCardList(), getBalance()]);
    if (res1.data?.cardList.length > 0) {
        const { bankName, cardNo, agreementNo } = res1.data.cardList[0];
        state.bankCardNumber = `${bankName}  (${cardNo})`;
        state.money = floatDivide(res2.data.money, 100).toFixed(2);
        form.agreementNo = agreementNo;
    }
    state.balance = `￥${state.money}`;
};
// 账户收支明细-列表
const getList = async () => {
    const { data } = await request('queryCapitalListServ', dealObjectEmptyValue(params));
    state.list = data.list || [];
    state.total = data.totalCount || 0;
};

// 查询
const onSearch = () => {
    params.page = 1;
    getList();
};
// 清空
const paramsRef = ref();
const onReset = () => {
    paramsRef.value.resetFields();
    params.page = 1;
    getList();
};
// 页码条数变更
const changeSizeHandler = v => {
    params.page = 1;
    params.perPage = v;
    getList();
};

// 页码变更
const changePageHandler = v => {
    params.page = v;
    getList();
};

// 页面跳转
const viewOrderDetail = row => {
    window.open(location.origin + `/order/list/detail?orderId=${row.orderId}&shopId=${row.shopId}`);
};

// 查看未结算订单tab
const viewSettleOrder = () => {
    if (hasOrderIncomeAuth.value && state.waitOrderIncome > 0) {
        emit('changeTab', 'unsettle');
    }
};

// 导出
const onExport = () => {
    request('capitalExportServ', dealObjectEmptyValue(params)).then(res => {
        exportExc(res, '账户收支明细导出');
    });
};

// 获取收入金额
const queryAmount = async () => {
    const { data } = await request('queryCapitalAmountServ');
    state.waitOrderIncome = floatDivide(data?.waitOrderIncome || 0, 100).toFixed(2);
    state.waitSubAccountIncome = `￥${floatDivide(data?.waitSubAccountIncome || 0, 100).toFixed(2)}`;
};

onMounted(() => {
    getData();
    queryAmount();
});
</script>

<style lang="scss" src="./account.scss" scoped></style>
